package nioserver;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * 请求处理程序
 * 
 * 请求处理程序是真正的业务处理代码。本例中主要负责读取客户端 socket 写入的数据，
 * 然后把当前的 SelectionKey 取消，让下一次 select 操作忽略掉当前的 SelectionKey. 
 * 这个类中使用了 Charset 辅助类来完成把读取的字节反编成一个可读的字符串。
 * 
 * @author Xinz
 *
 */
public class NIORequestHandler extends Thread {

	private SelectionKey selectionKey;
	private static Charset utf8 = Charset.forName("utf-8");
	
	public NIORequestHandler(SelectionKey selectionKey) {
		this.selectionKey = selectionKey;
	}
	
	@Override
	public void run() {
		SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		try {
			// 确保socketChannel连接
			if(!socketChannel.isConnected())
				socketChannel.finishConnect();
			
			// 读取数据并输出
			while(socketChannel.read(buffer) > 0 ) {
				buffer.flip();
				System.out.println(utf8.decode(buffer));
				buffer.clear();
			}
			
			// 移除selectionKey
			selectionKey.cancel();
		}
		catch(IOException e) {
			e.printStackTrace();
		}
	}
}
